package org.wu.framework.lazy.orm.database.sql.expand.database.persistence.method.dml;

import lombok.extern.slf4j.Slf4j;
import org.wu.framework.lazy.orm.core.factory.LazyTableUpsertConverterFactory;
import org.wu.framework.lazy.orm.database.lambda.domain.PersistenceRepository;
import org.wu.framework.lazy.orm.database.lambda.stream.LambdaTableType;
import org.wu.framework.lazy.orm.database.sql.expand.database.persistence.method.AbstractLazyOperationMethod;
import org.wu.framework.lazy.orm.database.sql.expand.database.persistence.method.LazyOperationParameter;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * @author : Jia wei Wu
 * @version 1.0
 * describe : upsert map 操作
 * @date : 2020/7/3 下午10:28
 */
@Slf4j
public class LazyOperationMethodWeakUpsert extends AbstractLazyOperationMethod {


    public LazyOperationMethodWeakUpsert(LazyOperationParameter lazyOperationParameter) {
        super(lazyOperationParameter);
    }

    /**
     * description 通过参数获取持久性存储库对象
     *
     * @param sourceParams 原始数据参数
     * @return 执行返回结果
     * @author Jia wei Wu
     * @date 2021/4/17 3:38 下午
     **/
    @Override
    public PersistenceRepository doAnalyzePersistenceRepository(Object[] sourceParams) throws Exception {
        String schema = (String) sourceParams[0];
        String table = (String) sourceParams[1];
        Object data = sourceParams[2];
        // TODO 深度解析问题
        String sql = LazyTableUpsertConverterFactory.upsertWeak(schema,table,data);
        PersistenceRepository persistenceRepository = createPersistenceRepository();
        persistenceRepository.setExecutionType(LambdaTableType.INSERT);
        persistenceRepository.setQueryString(sql);

        return persistenceRepository;
    }

    /**
     * description 执行SQL 语句
     *
     * @param connection 数据库连接
     * @param sourceParams 原始数据参数
     * @author Jia wei Wu
     * @date 2020/11/22 上午11:02
     */
    @Override
    public Object doExecute(Connection connection, Object[] sourceParams) throws Exception {
        accurateDoExecution(connection, sourceParams);
        return sourceParams.length;
    }

    /**
     * @param connection 数据源
     * @param param      单个对象或是单条记录
     * @return describe 精准执行
     * @author Jia wei Wu
     * @date 2021/4/26 5:12 下午
     */
    @Override
    public Object accurateDoExecution(Connection connection, Object param) throws Exception {
        PersistenceRepository persistenceRepository = analyzePersistenceRepository((Object[]) param);
        String queryString = persistenceRepository.getQueryString();
        PreparedStatement preparedStatement = connection.prepareStatement(queryString);
        try {
            final boolean execute = preparedStatement.execute();
            return execute;
        } catch (Exception e) {
            throw new SQLException(queryString, e);

        } finally {
            preparedStatement.close();
        }
    }
}
